<?php
/**
 * Created by jingjingxyk.
 * User: yaokun
 * Date: 17-7-18
 * Time: 下午11:51
 */

namespace ContentOutputBundle\Services;

use DBBundle\Entity\Books;
use DBBundle\Entity\Author;
use DBBundle\Entity\BookAuthor;
use DBBundle\Entity\Cate;

class ContentOutputBook
{
    private $em;

    public function __construct($em)
    {
        $this->em = $em;
    }

    /**
     * @param $book_id
     * @return array
     * 获取书籍基本信息
     */
    public function getBookInfo($book_id)
    {
        $repository = $this->em->getRepository(Books::class);

        $query = $repository->createQueryBuilder('p')
            ->where('p.bookId =:book_id')
            ->setParameter('book_id', $book_id)
            ->getQuery();
        $book = $query->getArrayResult();

        $book_info = isset($book[0]) ? $book[0] : [];
        if(!empty($book_info) ){
            $author = $this->getBookAuthor($book_id);
            if(empty($author)){
                $book_info["author_id"]=0;
                $book_info["author_name"]='';
                $book_info["author_intro"]='';
            }else{
                $book_info["author_id"] = $author["author_id"];
                $book_info["author_name"] = $author["author_name"];
                $book_info["author_intro"] = $author["author_intro"];
            }
            return $book_info;
        }

        return $book_info;
    }

    /**
     * @param $book_id
     * @return array
     * 通过书号获取作者信息
     */
    public function getBookAuthor($book_id)
    {
        $author = [];
        $book_author = $this->em->getRepository(BookAuthor::class)
            ->findOneBy([
            "bookId" => $book_id
            ]);
        if ($book_author) {
            $author_id = $book_author->getAuthorId();
            $author_obj = $this->em->getRepository(Author::class)
                ->findOneBy(["authorId" => $author_id]);
            if ($author_obj) {
                $author["author_id"] = $author_obj->getAuthorId();
                $author["author_name"] = $author_obj->getAuthorName();
                $author["user_id"] = $author_obj->getUserId();
                $author["author_intro"] = $author_obj->getAuthorIntro();
                $author["retrieval"] = $author_obj->getRetrieval();
            }
        }
        return $author;
    }

    /**
     * 获得书籍分类
     */
    public function getBookCategory()
    {

        $repository = $this->em->getRepository(Cate::class);
        $query = $repository->createQueryBuilder('p')->getQuery();
        return $query->getArrayResult();

    }

    public function __destruct()
    {
        unset($this->em);
    }
}